package com.example.fw;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public abstract class WebDriverHelperBase extends HelperBase {
	
	protected WebDriver driver;
	public boolean acceptNextAlert = true;
	private WebDriverWait wait;
	
	
	public WebDriverHelperBase(ApplicationManager manager) {
		super(manager);
		this.driver = manager.getDriver();
		wait = new  WebDriverWait(driver, 10);
	}

	public boolean isElementPresent(By by) {
	    try {
	    	driver.findElement(by);
	      return true;
	    } catch (NoSuchElementException e) {
	      return false;
	    }
	  }

	public String closeAlertAndGetItsText() {
	    try {
	      Alert alert = driver.switchTo().alert();
	      if (acceptNextAlert) {
	        alert.accept();
	      } else {
	        alert.dismiss();
	      }
	      return alert.getText();
	    } finally {
	    	acceptNextAlert = true;
	    }
	  }

	// in KEEP mode: updates element text by locator if 'text' variable is not empty. Otherwise element text is not updated.
	// in OVERWRITE mode: updates element text by locator if 'text' variable is not null. Otherwise element text is not updated.
	protected void type(By locator, String text, boolean mode) {
		if (text != null) {
			if (mode == KEEP) {
				if (text.isEmpty() == false) {
					driver.findElement(locator).clear();
			    driver.findElement(locator).sendKeys(text);
				}
			} else {
				driver.findElement(locator).clear();
		    driver.findElement(locator).sendKeys(text);
			}
		}
	}

	protected void click(By locator) {
		driver.findElement(locator).click();
	}

	protected void selectByText(By locator, String text) {
		if (text != null) {
			new Select(driver.findElement(locator)).selectByVisibleText(text);		
		}
	}

	protected void clickImage(By locator) {
		driver.findElement(locator).click();
	}

}
